package com.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.demo.dto.User;
import com.demo.service.AmqSenderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Service
public class AmqSenderServiceImpl implements AmqSenderService {

    private static final Logger logger = LoggerFactory.getLogger(AmqSenderServiceImpl.class);

    @Resource(name = "jmsTemplate")
    private JmsTemplate jmsTemplate;

    //目的地队列的明证，我们要向这个队列发送消息
    @Resource(name = "destinationQueue")
    private Destination destinationQueue;

    //目的地队列的明证，我们要向这个队列发送消息
    @Resource(name = "destinationTopic")
    private Destination destinationTopic;

    @Override
    public void sendQuenMsg(User user) {
        final String msg = JSON.toJSONString(user);
        try {
            logger.info("将要向队列{}发送的消息msg:{}", destinationQueue, msg);
            jmsTemplate.send(destinationQueue, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createTextMessage(msg);
                }
            });
        } catch (Exception ex) {
            logger.error("向队列{}发送消息失败，消息为：{}", destinationQueue, msg);
        }
    }

    @Override
    public void sendTopicMsg(User user) {
        final String msg = JSON.toJSONString(user);
        try {
            logger.info("将要向top队列{}发送的消息msg:{}", destinationTopic, msg);
            jmsTemplate.send(destinationTopic, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createTextMessage(msg);
                }
            });
        } catch (Exception ex) {
            logger.error("向top队列{}发送消息失败，消息为：{}", destinationTopic, msg);
        }
    }


}
